#include <assert.h>

#include <algorithm>
#include <array>
#include <cmath>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <set>
#include <utility>
#include <vector>

class Solution {
 public:
  int totalFruit(std::vector<int>& fruits) {
    long l = 0, r = 0;
    int max_disance = 0;

    while (1) {
      for (; r != fruits.size() && !is_three_tree_and_update(fruits[r], r); ++r)
        ;
      max_disance = ((r - l) > max_disance) ? (r - l) : max_disance;
      if (r == fruits.size()) {
        break;
      }

      auto iter = vec_lastIndex_.begin();
      if (iter->first == fruits[r - 1]) {
        ++iter;
      }

      l = iter->second + 1;
      vec_lastIndex_.erase(iter);
    }

    return max_disance;
  }

 private:
  bool is_three_tree_and_update(int val, int index) {
    if (vec_lastIndex_.size() == 0) {
      vec_lastIndex_.emplace_back(val, index);
      return false;
    }

    if (vec_lastIndex_.size() == 1) {
      if (vec_lastIndex_.front().first != val) {
        vec_lastIndex_.emplace_back(val, index);
      } else {
        vec_lastIndex_.front().second = index;
      }
      return false;
    }

    for (auto iter = vec_lastIndex_.begin(); iter != vec_lastIndex_.end();
         ++iter) {
      if (iter->first == val) {
        iter->second = index;
        return false;
      }
    }

    return true;
  }

 private:
  std::list<std::pair<int, int>> vec_lastIndex_;
};
